package com.sanalkitaplik.hibernateutil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.hibernate.Query;
import org.hibernate.Session;

import com.sanalkitaplik.packageclassdto.UsersInfoDTO;
import com.sanalkitaplik.packageclassdto.UsersLoginInfoDTO;

public class UsersUtil {
	
	private static Session session = null;
	
	/* Check işlemi doğruysa eğer FALSE döndürecek. */
	public static boolean loginCheck(String username, String user_pass){
		try{
			session = SessionFactoryBuilder.getSessionFactory().openSession(); 
			
			Query query = session.createSQLQuery("select USERNAME, USER_PASSWORD " +
										"from SNLKTPLK_USERS_LOGIN_INFO " +
										"where USERNAME = '"+username+"' and USER_PASSWORD = '"+user_pass+"'");
			
			if(!query.list().isEmpty())
				return false;
			return true;
			
		}
		catch(Exception ex){
			System.out.println("An exception occured while searching : " +ex.getMessage());
			return true;
		}
		finally{
			session.flush();
			session.close();
		}
	}
	
	public static void userRegister(UsersInfoDTO infoDto, UsersLoginInfoDTO logInfoDto, String type_name) throws SQLException{
		Connection connection = Connect.getConnection();
    	Statement stmt = connection.createStatement();
    	
    	ResultSet rs = stmt.executeQuery("select TYPE_ID from SNLKTPLK_TYPE_INFO where TYPE_NAME = '"+type_name+"'");
		long type_id = 0;
		if(rs.next())
			type_id = rs.getLong("TYPE_ID");
		
		String sql = "insert into SNLKTPLK_USERS_LOGIN_INFO values (default,'"+logInfoDto.getUsername()+"','"+logInfoDto.getUser_password()+"','"+logInfoDto.getUser_email()+"')";
		
		String sql2 = "insert into SNLKTPLK_USERS_INFO values (" +
				"(select USER_ID from SNLKTPLK_USERS_LOGIN_INFO where USERNAME='"+logInfoDto.getUsername()+"')," +
				"'"+infoDto.getFirst_name()+"'," +
						"'"+infoDto.getLast_name()+"'," +
								""+type_id+")";
		
		stmt.executeUpdate(sql);
		stmt.executeUpdate(sql2);
		
		connection.close();
		stmt.close();
		rs.close();
	}
}
